//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<engine_debug.cpp>
///	@path	~/src/engine/xcore/
///	@date	2007/11/10
///	@desc	Method for engine debug.

#include "config/config.h"

#include "lib/utilities/observer.h"

#include "object/CVar.h"

#include "engine/xcore/xeres_engine.h"

namespace xeres {

	// ctor
	EngineDebug::EngineDebug( void )
		: m_fpsStatElapse(0)
		, m_fpsAcc(0)
	{
	}

	// dtor
	EngineDebug::~EngineDebug( void )
	{
	}

	void EngineDebug::Initialize( RefWeak<IRenderer> renderer )
	{
		// make fps display
		m_fps = new CVar;
		m_fps->SetString( _S("fps:0") );

		m_canvas = new CCanvas;
		m_canvas->Initialize( renderer );

		m_fpsFont = renderer->CreateFont(
			_S("Verdana") , 18 , 0 , 400 , false , true , true );

		m_fpsText = new CCanvasText( m_fps , m_fpsFont , DT_CENTER | DT_VCENTER , Color4(1,1,1,1) );

		m_canvas->AddElement( m_fpsText );

		// import observer to data entry
	}

	void EngineDebug::Finalize( void )
	{
		// MUST !!!! release all references
		m_fps = NULL;
		m_fpsFont = NULL;
		m_fpsText = NULL;
		m_canvas = NULL;
	}

	void EngineDebug::Tick( const Frame& frame )
	{
		COUNTER_GUARD( _S("debug") );

		// FIXME! should take this to $ stage
// 		m_fpsAcc += 1;
// 		m_fpsStatElapse += frame.dtime();
// 
// 		// update fps
// 		if( m_fpsStatElapse >= 0.2 )
// 		{
// 			double fps = m_fpsAcc / m_fpsStatElapse;
// 			m_fpsAcc = m_fpsStatElapse = 0;
// 
// 			wchar_t buffer[128];
// 			swprintf( buffer , _S("fps:%.f") , fps );
// 			m_fps->SetString( WString( buffer ) );
// 		}

		m_fpsAcc += 1;
		//m_fpsStatElapse += frame.dtime();

		// update fps
		if( m_fpsStatElapse >= 200 )
		{
			double fps = m_fpsAcc / ( m_fpsStatElapse / 1000.f );
			m_fpsAcc = m_fpsStatElapse = 0;

			wchar_t buffer[128];
			swprintf( buffer , _S("fps:%.f") , fps );
			m_fps->SetString( WString( buffer ) );
		}
	}

	void EngineDebug::Render( RenderContext& rc )
	{
		int x = rc.ResX<int>();
		int y = rc.ResY<int>();

		m_fpsText->SetRect( Rect<int>( x/2-30 , 10 , x/2+150 , 30 ) );
		// should update some info
		m_canvas->Render( rc );
	}
	// StatEngineTime
	void EngineDebug::StatEngineTime( double ms )
	{
		m_fpsStatElapse += ms;
	}
} // namespace xeres
